<?php

namespace app\admin\controller\caiwu;

use app\common\controller\Backend;
use think\Db;
use app\admin\model\caiwu\Money;
use app\common\controller\MyHelp;
use app\api\controller\Pay;

/**
 * 提现
 *
 * @icon fa fa-circle-o
 */
class Tixian extends Backend
{

    /**
     * Tixian模型对象
     * @var \app\admin\model\caiwu\Tixian
     */
    protected $model = null;
    protected $dataLimit = true;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\caiwu\Tixian;
        $this->view->assign("statussList", $this->model->getStatussList());
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("zztypeList", $this->model->getZztypeList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model

                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['admin_id', 'id', 'money', 'money2', 'statuss', 'msg', 'updatetime', 'type', 'addtime', 'orderno', 'order']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $all = round(db::table('fa_tixian')->where('admin_id', $this->auth->id)->sum('money'), 2);
        $admin = db::table('fa_admin')->where('id', $this->auth->id)->find();
        $money = $admin['money'];
        $this->assign('all', $all);
        $this->assign('money', $money);
        if ($this->auth->id == 1) {
            $visible = "false";
        } else {
            $visible = "true";
        }
        $this->assign('visible', $visible);
        return $this->view->fetch();
    }
    /**
     * 申请提现
     */
    public  function withdraw()
    {
        $admin = db::table('fa_admin')->where('id', $this->auth->id)->find();
        if ($this->request->isPost()) {
            $txmoney = $this->request->request('txmoney');
            if ($txmoney < 10) {
                return $this->error('提现金额最低10元');
            }
            // return (float)$txmoney;
            if (MyHelp::strexists($txmoney, '.')) {
                return $this->error('提现金额要为整数');
            }
            if ($admin['money'] < $txmoney) {
                return $this->error('余额不足，无法提现');
            }
            if (!$admin['openid']) {
                return $this->error('请先到个人资料处绑定微信');
            }
            $ssss =   Db::table('fa_tixian')->where('admin_id', $this->auth->id)->whereTime('addtime', 'today')->find();
            if ($ssss) {
                return $this->error('每天最多提现一次，请明天再来');
            }

            $order = 'TR' . date('YmdHis') . rand(1111111, 9999999);
            $new = [
                'admin_id' => $this->auth->id,
                'money' => $txmoney,
                'money2' => $txmoney,
                'msg' => '待处理',
                'openid' => $admin['openid'],
                'type' => '2',
                'addtime' => time(),
                'order' => $order
            ];
            Db::table('fa_tixian')->insert($new);

            $before = $admin['money'];
            //更新累计提现
            $alltx = round(db::table('fa_tixian')->where('admin_id', $this->auth->id)->sum('money'), 2);
            db::table('fa_admin')->where('id', $this->auth->id)->update(['alltx' => $alltx]);

            $new_money = round($before - $txmoney, 2);
            Money::create(['admin_id' => $this->auth->id, 'type' => '6', 'money' => $txmoney * -1, 'before' => $before, 'after' => $new_money, 'memo' => '余额提现', 'type1' => 1, 'orderPc' => $order]);
            db::table('fa_admin')->where('id', $this->auth->id)->update(['money' => $new_money]);

            $pay = new pay();
            $rst =   $pay->toBalance($admin['openid'], intval($txmoney * 100), '余额提现', $order, 'wx6a20a1300ba9e158');
            //{"batch_id":"131000011083401975372722023122713330820322","batch_status":"ACCEPTED","create_time":"2023-12-27T20:38:40+08:00","out_batch_no":"sdfd111111111"}
            $rst_arr = json_decode($rst, true);
            ////{"code":"PARAM_ERROR","detail":{"location":"body","value":""},"message":"无法将 JSON 输入源“/body/total_amount”映射到目标字段“转账总金额”中，此字段需要一个合法的 64 位有符号整数"}
            MyHelp::dingding('话费订单提现：' . $rst, '3acdcd1692e6ca3fee6bf21ba73c6a837e1ff69b95d63a4be3c7bd3df25886b6');

            if (isset($rst_arr['code'])) {
                Db::table('fa_tixian')->where('order', $order)->update(['msg' => '人工审核中']);
                return $this->error($rst_arr['message']);
            } else {
                Db::table('fa_tixian')->where('order', $order)->update(['statuss' => '0', 'msg' => '打款中', 'orderno' => $rst_arr['batch_id']]);
                return $this->success('提交成功');
            }


            // return $this->success('提交成功');
        }

        $money = $admin['money'];
        $this->assign('money', $money);
        return $this->view->fetch();
    }
    /**
     * 处理 
     */
    public function hand($ids)
    {
        $row = $this->model->get($ids);
        if ($this->request->isPost()) {
            if ($row['statuss'] != '0' && $row['statuss'] != '2') {
                return $this->error('订单已处理');
            }
            $pay = new pay();
            $rst =   $pay->toBalance($row['openid'], intval($row['money'] * 100), '余额提现', $row['order'] . 'A', 'wx6a20a1300ba9e158');
            //{"batch_id":"131000011083401975372722023122713330820322","batch_status":"ACCEPTED","create_time":"2023-12-27T20:38:40+08:00","out_batch_no":"sdfd111111111"}
            $rst_arr = json_decode($rst, true);
            ////{"code":"PARAM_ERROR","detail":{"location":"body","value":""},"message":"无法将 JSON 输入源“/body/total_amount”映射到目标字段“转账总金额”中，此字段需要一个合法的 64 位有符号整数"}
            MyHelp::dingding('话费订单提现：' . $rst, '3acdcd1692e6ca3fee6bf21ba73c6a837e1ff69b95d63a4be3c7bd3df25886b6');
            if (isset($rst_arr['code'])) {
                return $this->error($rst_arr['message']);
            } else {
                $row->statuss = '0';
                $row->orderno = $rst_arr['batch_id'];
                $row->msg = '审核成功';
                $row->order = $row['order'] . 'A';
                $row->save();
                return $this->success('处理成功');
            }
        }
    }
}
